//
//  MatchController.m
//  cutter
//
//  Created by mac on 15/12/14.
//  Copyright © 2015年 e360. All rights reserved.
//
#import "ProductDetailCtrl.h"
#import "MatchEdit.h"
//
//
@implementation MatchEditCell
-(void)setSelected:(BOOL)selected{
    [super setSelected:selected];
    if (selected) {
        [self.maskView setAlpha:1.0];
    }else{
        [self.maskView setAlpha:0.6];
    }
}
@end
//
//
@implementation MatchEdit
- (void)viewDidLoad {
    [super viewDidLoad];
    //
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] init];
    [self.view addGestureRecognizer:pan];
    [pan setCancelsTouchesInView:NO];
    //
    [self.bottomLayout setConstant:-528];
    [[TMCutterLayer property] setValue:AppDataRoot forKey:@"basePath"];
    //
    [self.ctrlView setHidden:YES];
    [self.undoView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.redoView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.delView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.botView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.flpView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.cpyView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.locView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.repView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.infView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    //
    [self.addView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.repView addTarget:self action:@selector(ctrlTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self updataMatch];
    //
    if (self.onSelected) {
        [self.exitView setImage:[UIImage imageNamed:@"btn_Top_Close_nor.png"] forState:UIControlStateNormal];
        [self.exitView setImage:[UIImage imageNamed:@"btn_Top_Close_arc.png"] forState:UIControlStateHighlighted];
    }
}
//
-(void)import:(NSDictionary*)data{
    [self.data removeAllObjects];
    //
    [self.data setValue:[TMJSON parse:[data objectForKey:@"json"]] forKey:@"json"];
    [self.data setValue:[data objectForKey:@"clientuuid"] forKey:@"clientuuid"];
    [self.data setValue:[data objectForKey:@"matchname"] forKey:@"matchname"];
    [self.data setValue:[data objectForKey:@"classids"] forKey:@"classids"];
    [self.data setValue:[data objectForKey:@"clientid"] forKey:@"clientid"];
    [self.data setValue:[data objectForKey:@"author"] forKey:@"author"];
    [self.data setValue:[data objectForKey:@"length"] forKey:@"length"];
    [self.data setValue:[data objectForKey:@"height"] forKey:@"height"];
    [self.data setValue:[data objectForKey:@"width"] forKey:@"width"];
    [self.data setValue:[data objectForKey:@"price"] forKey:@"price"];
    [self.data setValue:[data objectForKey:@"desc"] forKey:@"desc"];
    [self.data setValue:[data objectForKey:@"uuid"] forKey:@"uuid"];
    [self.data setValue:[data objectForKey:@"id"] forKey:@"id"];
    //
    [self updataMatch];
}
-(BOOL)save:(blockEvent)callback{
    if ([self needSaved]) {
        [self setSaveCallBack:callback];
        //
        __weak MatchEdit *this = self;
        [UIAlertController show:nil message:@"是否要保存此搭配?" buttons:@[@"是",@"否"] handler:^(UIAlertAction *action) {
            if ([action.title isEqualToString:@"是"]){
                [this performSegueWithIdentifier:@"saveSegue" sender:nil];
                if (this.saveCallBack) {
                    this.saveCallBack(this, nil);
                }
            }else{
                if (this.saveCallBack) {
                    this.saveCallBack(this, self.data);
                }
            }
        }];
        return YES;
    }
    [self setSaveCallBack:nil];
    return NO;
}
-(BOOL)needSaved{
    return self.cutterView.change;
}
//
-(void)updataMatch{
    if (self.isViewLoaded == NO) {
        return;
    }
    //
    id json = [self.data objectForKey:@"json"];
    if (json) {
        if ([json isKindOfClass:NSString.class]){
            json = [TMJSON parse:json];
            [self.data setValue:json forKey:@"json"];
        }
        //
        NSArray *items = [json objectForKey:@"identifier"];
        if ([items count] > 0) {
            __weak MatchEdit *this = self;
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSMutableDictionary *census = [NSMutableDictionary dictionary];
                for (id item in items) {
                    [census setValue:[NSNumber numberWithBool:YES] forKey:item];
                }
                NSArray *products = [AppData productDetail:[census.allKeys componentsJoinedByString:@","]];
                //
                [this.products removeAllObjects];
                for (id product in products) {
                    id iid = [product objectForKey:@"id"];
                    [this.products setValue:product forKey:iid];
                    [AppData productAttribute:product all:NO];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUDForView:this.view animated:YES];
                    [this.cutterView import:json];
                });
            });
        }
    }
}
//
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    TMCutterLayer *layer = self.cutterView.focusObject;
    if (layer != nil) {
        if (self.ctrlView.hidden) {
            [self.ctrlView setHidden:NO];
            [self.view.layer addAnimation:[CATransition animation] forKey:nil];
        }
        //产品
        if (layer.identifier) {
            id product = [self.products objectForKey:layer.identifier];
            if (product) {
                [self.thumb removeAllObjects];
                for (id item in [product objectForKey:@"images"]) {
                    [self.thumb addObject:[item objectForKey:@"thumb600"]];
                }
                //
                [self.thumbView reloadData];
                if (self.thumb.count > 0) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
                    NSInteger index = [self.thumb indexOfObject:[(id)layer image]];
                    if (index != NSNotFound) {
                        indexPath = [NSIndexPath indexPathForItem:index inSection:0];
                    }
                    [self.thumbView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
                }
            }
        }else{
            [self.thumbView reloadData];
        }
        [self.locView setSelected:!layer.enabled];
        [self updataCtrlItems];
    }else{
        if (self.ctrlView.hidden==NO) {
            [self.ctrlView setHidden:YES];
            [self.view.layer addAnimation:[CATransition animation] forKey:nil];
        }
    }
    //
    [self.bottomLayout setConstant:-528];
    [UIView beginAnimations:nil context:nil];
    [self.view layoutIfNeeded];
    [UIView commitAnimations];
}
- (void)presentController:(UIViewController*)controller{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        UIViewController *root = [[self.view window] rootViewController];
        if (root) {
            [root setModalPresentationStyle:UIModalPresentationCurrentContext];
            [root presentViewController:controller animated:NO completion:nil];
        }
    }else{
        [controller setModalPresentationStyle:UIModalPresentationOverCurrentContext];
        [self presentViewController:controller animated:NO completion:nil];
    }
}
- (IBAction)exitTouch:(UIButton*)sender{
    if (self.onSelected) {
        self.onSelected(self, self.data);
    }else{
        IndexHomeCtrl *tabbar = (id)self.splitViewController;
        if ([tabbar isKindOfClass:IndexHomeCtrl.class]) {
            [tabbar showMenu];
        }
    }
}
- (void)updataCtrlItems{
    if (self.locView.selected) {
        [self.repView setEnabled:NO];
        [self.topView setEnabled:NO];
        [self.botView setEnabled:NO];
        [self.flpView setEnabled:NO];
        [self.cpyView setEnabled:NO];
        [self.delView setEnabled:NO];
    }else{
        [self.repView setEnabled:YES];
        [self.topView setEnabled:YES];
        [self.botView setEnabled:YES];
        [self.flpView setEnabled:YES];
        [self.cpyView setEnabled:YES];
        [self.delView setEnabled:YES];
    }
}
- (void)ctrlTouch:(UIButton*)sender{
    if (sender == self.addView || sender == self.repView) {
        [self.bottomLayout setConstant:0];
        [UIView beginAnimations:nil context:nil];
        [self.view layoutIfNeeded];
        [UIView commitAnimations];
        //
        __weak MatchEdit *this = self;
        AssetsCenterCtrl *ctrl = self.assetsCenter;
        [ctrl setOnSelected:^(id target, id result){
            [this.thumb removeAllObjects];
            //
            TMCutterImage *img = nil;
            if (sender == this.repView) {
                img = (id)[this.cutterView focusObject];
            }else{
                img = [TMCutterImage layer:nil];
                [this.cutterView addChild:img];
                [this.cutterView setFocusObject:img];
            }
            if(img && [img isKindOfClass:TMCutterImage.class]){
                if ([target isKindOfClass:ProductCenterCtrl.class] || [target isKindOfClass:ProductFavoriteCtrl.class]) {
                    id detail = [[AppData productDetail:[result objectForKey:@"id"]] firstObject];
                    if (detail) {
                        [AppData productAttribute:detail all:YES];
                        [this.products setValue:detail forKey:[detail objectForKey:@"id"]];
                        for (id item in [detail objectForKey:@"images"]) {
                            [this.thumb addObject:[item objectForKey:@"thumb600"]];
                        }
                        [img setIdentifier:[result objectForKey:@"id"]];
                    }
                }else{
                    [this.thumb addObject:[result objectForKey:@"pic"]];
                    [img setIdentifier:nil];
                }
                //
                NSString *src = [this.thumb firstObject];
                if (src) {
                    [img setImage:src];
                }
                //
                [this.thumbView reloadData];
                //
                if (this.thumb.count > 0) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
                    [this.thumbView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
                }
            }
        }];
        return;
    }
    //
    if (sender == self.undoView || sender == self.redoView) {
        if (sender == self.undoView) {
            [self.cutterView undo];
        }else{
            [self.cutterView redo];
        }
        return;
    }
    //
    TMCutterLayer *layer = self.cutterView.focusObject;
    if (layer) {
        if (sender == self.delView) {
            [self.cutterView removeChild:layer];
            [self.ctrlView setHidden:YES];
        }
        if (sender == self.topView) {
            NSInteger i = [self.cutterView getChildIndex:layer];
            [self.cutterView setChildIndex:layer index:i + 1];
        }
        if (sender == self.botView) {
            NSInteger i = [self.cutterView getChildIndex:layer];
            [self.cutterView setChildIndex:layer index:i - 1];
        }
        if (sender == self.flpView) {
            [layer setScaleX:layer.scaleX * -1];
            [self.cutterView setFocusObject:layer];
        }
        if (sender == self.locView) {
            [sender setSelected:!sender.selected];
            [layer setEnabled:!sender.selected];
            [self.cutterView setFocusObject:layer];
            [self updataCtrlItems];
        }
        if (sender == self.cpyView) {
            TMCutterLayer *clone = [layer.class layer:layer.data];
            [clone setX:layer.x + 10];
            [clone setY:layer.y + 10];
            [self.cutterView addChild:clone];
            [self.cutterView setFocusObject:clone];
        }
    }
}
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
    if ([identifier isEqualToString:@"saveSegue"]) {
        return [self needSaved];
    }
    if ([identifier isEqualToString:@"listSegue"]) {
        if ([self.products count] > 0) {
            return YES;
        }
        return NO;
    }
    if ([identifier isEqualToString:@"publishSegue"]) {
        if ([[self.data objectForKey:@"isshare"] boolValue] == NO) {
            if ([self needSaved]) {
                __weak typeof(self)this = self;
                [UIAlertController show:nil message:@"请保存当前搭配!" buttons:@[@"保存",@"取消"] handler:^(UIAlertAction *action) {
                    if ([action.title isEqualToString:@"保存"]){
                        [this performSegueWithIdentifier:@"saveSegue" sender:nil];
                    }
                }];
                return NO;
            }
        }
    }
    return YES;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    //产品列表
    if ([segue.destinationViewController isKindOfClass:AssetsCenterCtrl.class]) {
        [self setAssetsCenter:segue.destinationViewController];
        return;
    }
    //
    __weak MatchEdit *this = self;
    if ([segue.destinationViewController isKindOfClass:ProductListCtrl.class]) {
        if ([self.products count] > 0) {
            ProductListCtrl *ctrl = (ProductListCtrl*)segue.destinationViewController;
            [ctrl setData:self.products.allValues];
            [ctrl reloadData];
        }
        return;
    }
    //
    if ([segue.destinationViewController isKindOfClass:UINavigationController.class]) {
        UINavigationController *navigation = segue.destinationViewController;
        if ([[navigation.viewControllers firstObject] isKindOfClass:MatchSave.class]) {
            CGFloat price = 0;
            id json = [this.cutterView export];
            for (id pid in [json objectForKey:@"identifier"]) {
                id item = [this.products objectForKey:pid];
                if (item) {
                    price += [[item objectForKey:@"price"] floatValue];
                }
            }
            [self.cutterView setFocusObject:nil];
            [self.data setValue:[NSNumber numberWithFloat:price] forKey:@"price"];
            [self.data setValue:[self.cutterView snapshot] forKey:@"bitmap"];
            [self.data setValue:json forKey:@"json"];
            //
            MatchSave *save = [navigation.viewControllers firstObject];
            [save setOnSelected:^(id target, id result){
                [this dismissViewControllerAnimated:YES completion:^{
                    if (result) {
                        [MBProgressHUD showHUDAddedTo:this.view animated:YES];
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            [AppData userEditMatch:result bitmap:nil];
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [this.cutterView setChange:NO];
                                //[this.data setValue:[result objectForKey:@"uuid"] forKey:@"uuid"];
                                [MBProgressHUD hideHUDForView:this.view animated:YES];
                                //
                                if (this.saveCallBack) {
                                    this.saveCallBack(this, result);
                                }
                            });
                        });
                    }
                }];
            }];
            [save setData:this.data];
            return;
        }
        if ([[navigation.viewControllers firstObject] isKindOfClass:MatchPublish.class]) {
            if ([self.data objectForKey:@"bitmap"] == nil) {
                [self.cutterView setFocusObject:nil];
                [self.data setValue:[self.cutterView snapshot] forKey:@"bitmap"];
            }
            //
            MatchPublish *publish = [navigation.viewControllers firstObject];
            [publish setOnSelected:^(id target, id result){
                [this dismissViewControllerAnimated:YES completion:^{
                    if (result) {
                        [AppData userShareMatch:this.data];
                    }
                }];
            }];
            [publish setData:this.data];
            return;
        }
        if ([[navigation.viewControllers firstObject] isKindOfClass:ProductSynopsisCtrl.class]) {
            ProductSynopsisCtrl *ctrl = [navigation.viewControllers firstObject];
            TMCutterLayer *layer = self.cutterView.focusObject;
            if (layer != nil) {
                if (layer.identifier) {
                    id product = [self.products objectForKey:layer.identifier];
                    [ctrl setData:product];
                }
            }
            return;
        }
    }
}
//
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    TMCutterImage *layer = (id)self.cutterView.focusObject;
    if (layer && [layer isKindOfClass:TMCutterImage.class]) {
        [layer setImage:[self.thumb objectAtIndex:indexPath.item]];
    }
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.thumb count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MatchEditCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    [AppData loadImage:[self.thumb objectAtIndex:indexPath.item] view:cell.imageView];
    return cell;
}
//
//
-(NSMutableDictionary *)data{
    if (_data == nil) {
        [self setData:[NSMutableDictionary dictionary]];
    }
    return _data;
}
-(NSMutableDictionary *)products{
    if (_products == nil) {
        [self setProducts:[NSMutableDictionary dictionary]];
    }
    return _products;
}
-(NSMutableArray *)thumb{
    if (_thumb == nil) {
        [self setThumb:[NSMutableArray array]];
    }
    return _thumb;
}
@end
